import {Component, ElementRef, Input, Output, EventEmitter, OnInit, ViewChild, Injectable } from '@angular/core';
import {Util} from "../../../../common/util";
import {FileUploadNormalComponent} from '../../purchase/file-upload-normal/file-upload-normal.component';
import {ZQListService} from './zq-list.service';
import {AppPaginationComponent, PaginationModel} from '../../../../widgets/pagination/pagination.component';
import {environment} from '../../../../../environments/environment';
import * as moment from 'moment';
import * as _ from 'lodash';

// 中签搜索数据模型
export interface ZQSearchModel {
  // 划款状态
  hkInstructionStatus?: string;
  // 组合代码
  vcFundCode?: string;
  // 组合名称
  vcFundName?: string;
  // 证券代码
  vcNewstockId?: string;
  // 证券名称
  vcNewstockName?: string;
  // 配售公告日期开始
  zqDateStart?: string;
  // 配售公告日期结束
  zqDateEnd?: string;
  // 缴款日开始
  jkDateStart?: string;
  // 缴款日结束
  jkDateEnd?: string;
  // 查询日期（空表示当天）
  traceDate?: string;
  // 是否历史交易
  isHisData?: boolean;
  [propName: string]: any;
}

@Component({
  selector: 'new-stock-zq-list',
  templateUrl: './zq-list.component.html',
  styleUrls: ['./zq-list.component.scss'],
  providers: [ZQListService]
})
export class ZQListComponent implements OnInit {

  // 列表类型（1：中签管理，2：已缴款 3：申购中签管理）
  @Input()
  public type;

  public isShowBallot = true;

  // 列表
  public remittanceList: Array<any>;

  // 列表当前页全选标记
  public isCheckedAll = false;

  // 查询条件
  public searchBody:any = {
    // vcFundCode: "", // 基金代码
    // vcNewstockId: "", // 证券代码
    // type: "", // 列表类型（1：中签管理，2：已缴款 3：申购中签管理）
    // page: 1, // 页码
    // pageSize: environment.pageSize,
    // traceDate: "", // 查询日期（空表示当天）
    isHisData: false // 是否历史交易（true：历史，false：当前）
  };

  // 分页配置
  public pageInfo: PaginationModel = {
    currentPageNum: 1,
    pageSize: 10,
    totalPages: 1,
    total: 0,
    pagesShow: 5,
    startRow: 0,
    endRow: 0,
    pageList: [5, 10, 25, 50, 100]
  };

  // 指令及中签比对
  public mathResult = {
    "0": "未中签",
    "1": "匹配一致",
    "2": "匹配不一致",
    "3": "未中签（手工）",
    "4": "未下指令"
  };

  /**
   * 划款指令状态集合
   * @memberof ListComponent
   */
  public status: any = {
    "1": "待确认",
    "2": "待复核",
    "3": "初审驳回",
    "4": "待审核",
    "5": "复核驳回",
    "6": "待发送",
    "7": "发送托管行出款",
    "8": "手工到账确认",
    "9": "已到账",
    "10": "已撤销"
  };

  // 分页组件
  @ViewChild(AppPaginationComponent)
  public paginationComponent: AppPaginationComponent;

  // 导入配售对象
  @ViewChild(FileUploadNormalComponent)
  private fileUploadNormalComponent: FileUploadNormalComponent;

  constructor(public zQService: ZQListService) {
    // this.getRemittanceList(1);
  }

  ngOnInit() {
    this.search();
  }

  ngAfterViewInit(): void {
    Util.daterangepickerPluginInit(".daterangepicker-plugin");
  }

  changeBallotStatus() {
    this.isShowBallot = !this.isShowBallot;
  }

  /**
   * [search 查询]
   */
  search() {
    this.getRemittanceList(this.warpperSearchModule());
  }

  /**
   * [resetSearch 重置查询条件]
   */
  resetSearch() {
    window["$"](".ibt-search-input[type='text']").each(function () {
      this.value = "";
    });
    window["$"](".ibt-search-input").prop("checked", false);
  }


  /**
   * [checkedAll 列表当前页全选]
   */
  checkedAll() {
    if (this.isCheckedAll) { // 更新为全选
      _.forEach(this.remittanceList, item => {
        item.isChecked = true;
      });
    } else { // 更新为不全选
      _.forEach(this.remittanceList, item => {
        item.isChecked = false;
      });
    }
  }

  /**
   * [checked 是否需要更新全选]
   * @param {[type]} remittance [实例对象]
   */
  checked(remittance) {
    if (remittance.isChecked) {
      const temp = _.find(this.remittanceList, {isChecked: false});
      if (!temp) { // 全选重置为 true
        this.isCheckedAll = true;
      }
    } else { // 全选重置为 false
      this.isCheckedAll = false;
    }
  }


  /**
   * 获取row的pmkyNum，作为参数返回。用来执行手工到账确认
   * param [{
	 * 	remittance：//当前行数据，
	 * 	action: //手工操作编号
	 * }]
   */
  getDataToTransferredConfirm(remittance, action) {
    const search = {
      pmkyList: "",
      cDzStatus: [],
      vcDzUser:[],
      action: action
    };
    const pmkyArr = [];
    // 这里获取数据中的cDzStatus是为了判断是否符合操作资格
    remittance.forEach((item) => {
      pmkyArr.push(item.pmkyNum);
      search.cDzStatus.push(item.cDzStatus);
      search.vcDzUser.push(item.vcDzUser);
    });
    search.pmkyList = pmkyArr.join(",");
    return search;
  }

  /**
   * 获取row的pmkyNum，作为参数返回。用来执行中签标记
   * param [{
	 * 	remittance：当前行数据，
	 * 	zqFlag: 中签状态
	 * }]
   */
  getDataToMarkZQHandle(remittance, zqFlag) {
    const search = {
      lConfirmNo: [],
      matchResult: []
    };
    const matchResultArr = [];
    remittance.forEach((item) => {
      search.lConfirmNo.push({lConfirmNo: item.lConfirmNo, cZqFlag: zqFlag});
      matchResultArr.push(item.matchResult);
    });
    // search.lConfirmNo = lConfirmNo.join(",");
    search.matchResult = matchResultArr;
    return search;
  }

  // 包装查询条件
  public warpperSearchModule(): ZQSearchModel {
    const $ = window["$"];
    const data: ZQSearchModel = {
      cDzStatus: [],
      cMatchResult: []
    };
    $(".ibt-search-input").each((index, item) => {
      const $item = Util.$(item);
      const type = item.type;
      const id = item.id;
      const name = item.name;
      const value = item.value;
      const daterangepicker = $item.data('daterangepicker');
      if (id && id !== "") {
        if (id === "zqDate") {
          data[`${id}Start`] = (value != null && value.length > 0) ? daterangepicker.startDate.format('YYYYMMDD') : "";
          data[`${id}End`] = (value != null && value.length > 0) ? daterangepicker.endDate.format('YYYYMMDD') : "";
        } else if (id === "jkDate") {
          data[`${id}Start`] = (value != null && value.length > 0) ? daterangepicker.startDate.format('YYYYMMDD') : "";
          data[`${id}End`] = (value != null && value.length > 0) ? daterangepicker.endDate.format('YYYYMMDD') : "";
        } else {
          if (type === 'text' || type === 'select' || type === 'select-one') {
            data[id] = value;
          }
        }
      }
      if (type === 'radio' && item.checked) {
        data[name] = value;
      }
      if (type === 'checkbox' && item.checked) {
        if (name === "cDzStatus" || name === "cMatchResult") {
          data[name].push(value);
        } else {
          data[name] = value;
        }
      }
    });
    data.cMatchResult = data.cMatchResult.join(',');
    data.cDzStatus = data.cDzStatus.join(',');
    data.type = this.type;
    data.isHisData = this.searchBody.isHisData;
    return data;
  }

  /**
   * [getRemittanceList 会计划款列表]
   */
  getRemittanceList(search: ZQSearchModel,
                    currentPageNum: number = this.pageInfo.currentPageNum,
                    pageSize: number = this.pageInfo.pageSize) {
    this.zQService.getRemittanceList(search, currentPageNum, pageSize).subscribe(data => {
      if (data) {
        // 添加是否选择状态， 默认否
        _.forEach(data.list, item => {
          item.isChecked = false;
        });
        this.remittanceList = data.list;
        // 构建分页
				this.pageInfo.startRow = data.startRow;
        this.pageInfo.endRow = data.endRow;
        this.pageInfo.totalPages = data.pages;
        this.pageInfo.total = data.total; // 总记录数
      }
    });
  }

  /**
   * 当日中签入围&&当日缴款
   * @param selector 目标DOM元素的ID
   */
  setTimeToday(selector) {
    this.resetSearch();
    const initValue = moment(new Date()).format('YYYY-MM-DD') + ' 至 ' + moment(new Date()).format('YYYY-MM-DD');
    Util.$(selector).val(initValue);
    this.search();
  }

  /**
   * 到账异常
   * @param {any} data 
   * @memberof ZQListComponent
   */
  dzNotTrue(data){
    window["swal"]("提示", `中签金额是${data.enMoney}\n到账金额是${data.enDzMoney}\n中签金额与到账金额不一致！`, "info");
  }

  /**
   * 根据页码请求查询相关配置列表数据,如果当前活动页码就是目标页码，则不进行任何查询
   * 直接返回
   */
  public pageNavigation(currentPageNum: number) {
    this.pageInfo.currentPageNum = currentPageNum;
    this.getRemittanceList(
      this.warpperSearchModule(),
      this.pageInfo.currentPageNum,
      this.pageInfo.pageSize);
  }

  /**
   * 改变每页显示记录数
   * @param {pageSize}
   */
  public pageSizeChange(pageSize: number) {
    if (pageSize !== this.pageInfo.pageSize) {
      this.pageInfo.pageSize = pageSize;
      this.pageInfo.currentPageNum = 1;
      this.getRemittanceList(this.warpperSearchModule(), this.pageInfo.currentPageNum, this.pageInfo.pageSize,);
    }
  }

  /**
   * [reflesh 刷新]
   */
  reflesh() {
    this.resetSearch();
  }

  /**
   * [refleshCurrPage 刷新当前页面]
   */
  refleshCurrPage() {
    this.search();
  }

}
